﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCApplication.Helpers
{
    public class UrlHistory
    {
        protected const string SESSION_KEY = "urlHistorySession";

        protected static Stack<string[]> GetUrlHistory(HttpSessionStateBase session)
        {
            if ((session[SESSION_KEY] != null))
            {
                return (Stack<string[]>)session[SESSION_KEY];
            }
            else
            {
                return new Stack<string[]>();
            }
        }

        protected static void SetUrlHistory(HttpSessionStateBase session, Stack<string[]> urlHistory)
        {
            session[SESSION_KEY] = urlHistory;
        }

        public static string BackUrl(HttpSessionStateBase session)
        {
            string url = UrlHistory.Pop(session);
            if (url != null)
            {
                url = UrlHistory.Pop(session);
            }
            return url;
        }

        public static string Pop(HttpSessionStateBase session)
        {
            if ((session[SESSION_KEY] != null))
            {
                Stack<string[]> urlHistory = GetUrlHistory(session);
                if (urlHistory.Count > 0)
                {
                    string url = urlHistory.Pop()[1];
                    SetUrlHistory(session, urlHistory);
                    return url;
                }
            }
            return null;
        }

        public static void Push(HttpSessionStateBase session, Uri url)
        {
            Stack<string[]> urlHistory = GetUrlHistory(session);
            string lastUrlAbsolutePath = null;
            string[] lastUrl = null;
            if (urlHistory.Count > 0)
            {
                lastUrl = urlHistory.Pop();
                if (lastUrl == null)//discard next push
                    return;
                lastUrlAbsolutePath = lastUrl[0];
            }
            if (lastUrlAbsolutePath != null && lastUrlAbsolutePath != url.AbsolutePath.ToLower())
            {
                urlHistory.Push(lastUrl);
                urlHistory.Push(new string[] { url.AbsolutePath.ToLower(), url.PathAndQuery });
            }
            else
            {
                if (lastUrlAbsolutePath != null && url.PathAndQuery == url.AbsolutePath)
                {
                    urlHistory.Push(lastUrl);
                }
                else
                {
                    urlHistory.Push(new string[] { url.AbsolutePath.ToLower(), url.PathAndQuery });
                }
            }
            SetUrlHistory(session, urlHistory);
        }

        public static void DiscardNextPush(HttpSessionStateBase session)
        {
            Stack<string[]> urlHistory = GetUrlHistory(session);
            urlHistory.Push(null);
        }
    }
}
